package com.yly.test1

import android.accounts.NetworkErrorException
import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
import android.util.Log
import com.yly.test1.utils.ToastUtils
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import org.jsoup.Jsoup
import java.net.URLEncoder
import java.util.*

fun connectCampusNetwork(
    _userIndex: String?,
    shp: SharedPreferences,
    _queryString: String?,
    context: Context,
    userStudentNo: String?,
    userPassword: String?
) {
    println("userStudentNo:${userStudentNo} userPassword:${userPassword}")

    if (userStudentNo.isNullOrEmpty() || userPassword.isNullOrEmpty()) {
        return
    }
    val okHttpClient = OkHttpClient()

    try {
        userIsOnline(okHttpClient, _userIndex)
        Log.d("info", "userIsOnline 被调用 ")
    } catch (e: Exception) {
        if (e is NetworkErrorException) {
            ToastUtils.show(context, e.message)
        }
        ToastUtils.show(context, e.message)
        e.printStackTrace()
        return
    }

    var debug: String
    var loginSuccess = false
    var queryString = ""
    var userIndex = ""
    val service: String

    try {

        queryString =
            if (_queryString == null || _queryString.isBlank()) getQuerySting(okHttpClient) else _queryString

        service = getService(okHttpClient, userStudentNo, queryString)
        if (service.isEmpty()){
            return
        }

        val formBody: FormBody = FormBody.Builder()
            .add("userId", userStudentNo)
            .add("password", userPassword)
            .add("service", service)
            .add(
                "queryString",
                queryString
            )
            .add("operatorPwd", "")
            .add("operatorUserId", "")
            .add("validcode", "")
            .add("passwordEncrypt", "false")
            .build()
        val request: Request = Request.Builder()
            .post(formBody)
            .url("http://172.30.0.11/eportal/InterFace.do?method=login")
            .build()

        val response = okHttpClient.newCall(request).execute()
        debug = response.body!!.string()
        val data = JSONObject(debug)
        loginSuccess = data.getString("result").equals("success")
        userIndex = data.getString("userIndex")
        println(debug)
        ToastUtils.show(context, data.toString())
    } catch (e: Exception) {
        var debugTemp: String
        debugTemp = e.message.toString()
        if (e is StringIndexOutOfBoundsException) {
            // 这个也有可能是当前wifi能上网或者开启数据流量
            debugTemp = "当前设备能访问百度，但是不确定是否登录校园网"
        }
        debug = debugTemp

        e.printStackTrace()
        ToastUtils.show(context, debug)
    }
    if (queryString.isNotEmpty() && loginSuccess && userIndex.isNotEmpty()) {
        saveData(shp, userStudentNo, userPassword, queryString, userIndex)
    }
}

//private fun showToast(context: Context, debug: String) {
//    val toast = Thread {
//        Looper.prepare()
//        val toast = Toast.makeText(
//            context,
//            debug,
//            Toast.LENGTH_SHORT
//        )
//        toast.show()
//        Looper.loop()
//        Looper.myLooper()?.quit()
//    }
//    toast.start()
//}

@Throws(StringIndexOutOfBoundsException::class)
private fun getQuerySting(okHttpClient: OkHttpClient): String {
    val getQueryString: Request = Request.Builder()
        .get()
        .url("http://61.135.169.121/")
        .build()
    val queryStringResponse = okHttpClient.newCall(getQueryString).execute()
    val dom = Jsoup.parse(queryStringResponse.body!!.string())
    queryStringResponse.close()
    val strictData = dom.head().allElements[1].data()
    // 数据后面带一个单引号(')
    val dataWithApostrophe = strictData.substring(strictData.indexOfFirst { it == '?' } + 1)
    return dataWithApostrophe.substring(0, dataWithApostrophe.length - 1)
}

private fun saveData(
    shp: SharedPreferences,
    _userStudentNo: String,
    _userPassword: String,
    _queryString: String,
    _userIndex: String
) {
    val editor = shp.edit()
    if (!shp.getBoolean("appended", false)) {
        editor.putString("queryString", _queryString)
        editor.putString("userStudentNo", _userStudentNo)
        editor.putString("userPassword", _userPassword)
        editor.putString("userIndex", _userIndex)
        editor.putBoolean("appended", true)
        editor.apply()
    }
}

@Throws(Exception::class)
private fun userIsOnline(okHttpClient: OkHttpClient, _userIndex: String?) {
    if (_userIndex.isNullOrEmpty()) {
        return
    }
    val formBody = FormBody.Builder()
        .add("userIndex", _userIndex)
        .build()
    val queryUserInfo: Request = Request.Builder()
        .post(formBody)
        .url("http://172.30.0.11/eportal/InterFace.do?method=getOnlineUserInfo")
        .build()
    val queryUserInfoResponse = okHttpClient.newCall(queryUserInfo).execute()
    val dom = Jsoup.parse(queryUserInfoResponse.body!!.string())
    queryUserInfoResponse.close()
    val data = StringTokenizer(dom.body().allElements[0].childNode(0).toString(), ":").toList()
    val userName = StringTokenizer(data[7].toString(), ",").toList()[0].toString().replace("\"", "")
    val serviceName =
        StringTokenizer(data[15].toString(), ",").toList()[0].toString().replace("\"", "")
    // 当获取用户名为空可能是，没有连接上校园网
    if (userName == "null") {
        return
    }
    throw Exception("用户${userName}已在线,使用$serviceName")
}


@Throws(Exception::class)
private fun getService(
    okHttpClient: OkHttpClient,
    _userStudentNo: String?,
    _queryString: String?
): String {
    if (_userStudentNo.isNullOrEmpty() || _queryString.isNullOrEmpty()) {
        return ""
    }
    val formBody = FormBody.Builder()
        .add("username", _userStudentNo)
        .add("search", "?$_queryString")
        .build()
    val queryService: Request = Request.Builder()
        .post(formBody)
        .url("http://172.30.0.11/eportal/userV2.do?method=getServices")
        .build()
    val queryServiceResponse = okHttpClient.newCall(queryService).execute()
    val data = queryServiceResponse.body!!.string()
    val serviceDecode = StringTokenizer(data, "@").toList()[1].toString()
    return URLEncoder.encode(serviceDecode,Charsets.UTF_8.name())
}
